package com.xbongbong.formula.qlexpress.operator.date;

import com.ql.util.express.Operator;
import com.ql.util.express.OperatorOfNumber;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.PaasDateUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessRuleErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ProErrorCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2019/8/9 9:51
 * @since v1.0
 */
public class OperatorDateDelta extends Operator {

    public static final Logger LOGGER = LoggerFactory.getLogger(OperatorDateDelta.class);
    /**
     *  24 * 60* 60
     */
    private static final Integer SECOND = 86400;

    public OperatorDateDelta(String name){
        this.name = name;
    }

    public OperatorDateDelta(String aliasName, String aName, String errorInfo){
        this.aliasName = aliasName;
        this.name = aName;
        this.errorInfo = errorInfo;
    }

    /**
     * DATEDELTA(timestamp, deltadays)
     * 将指定日期加/减指定天数。
     * timestamp: 必需。初始日期。
     * deltadays: 必需。需要加减的天数。正数为增加，负数为减少。
     * @param list
     * @return 时间戳
     */
    @Override
    public Object executeInner(Object[] list) throws XbbException {

        if (Objects.isNull(list) || list.length != Constant.LENGTH) {
            throw new XbbException(BusinessRuleErrorCodeEnum.API_ERROR_261007);
        }
        try {
            if (list[0] == null || StringUtils.equals(list[0].toString(), Constant.ZERO_STRING)) {
                return null;
            }
            Long timestamp = PaasDateUtil.getInt(list[0]);
            Number day = (Number) list[1];

            Long second = day.longValue() * SECOND;
            return OperatorOfNumber.add(timestamp, second, true);
        } catch (Exception e) {
            LOGGER.error("OperatorDateDelta.executeInner 解析失败：", e);
            throw new XbbException(ProErrorCodeEnum.API_ERROR_260018);
        }
    }

}
